package com.ef.service.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.StatusType;
import com.ef.dao.ClassroomDao;
import com.ef.domain.Classroom;
import com.ef.service.ClassroomService;
import com.ef.util.CustomExample;
import com.ef.util.PaginationSupport;

public class ClassroomServiceImpl extends BaseServiceImpl implements
		ClassroomService {

	private ClassroomDao classroomDao;
	
	public PaginationSupport<Classroom> findByExample(
			CustomExample<Classroom> example, int startIndex, int pageSize) {

		return classroomDao.findPageByExample(example, startIndex, pageSize);
	}

	public void saveOrUpdate(Classroom entity) {
		//必须要
		classroomDao.clear();
		classroomDao.saveOrUpdate(entity);
	}

	public void delete(Classroom entity) {
		entity.setStatus(StatusType.INVALID
				);
		classroomDao.update(entity);
	}

	public Classroom findById(Long id) {
		return classroomDao.findById(id);
	}

	public ClassroomDao getClassroomDao() {
		return classroomDao;
	}

	public void setClassroomDao(ClassroomDao classroomDao) {
		this.classroomDao = classroomDao;
	}
	
	public List<Classroom> findAllValid() {
		DetachedCriteria criterion=DetachedCriteria.forClass(Classroom.class);
	    criterion.add(Restrictions.eq("status",
				StatusType.VALID));
	    return classroomDao.findAllByCriteria(criterion);
 	}
	
	public List<Classroom> findAllValidInSchool(Long schoolId){
		DetachedCriteria criterion=DetachedCriteria.forClass(Classroom.class);
		criterion.createCriteria("school").add(Restrictions.eq("id",schoolId));
	    criterion.add(Restrictions.eq("status",
				StatusType.VALID));
	    return classroomDao.findAllByCriteria(criterion);
 	}
	
	public List<Classroom> findByCapacityInSchool(Long schoolId,Integer caps) {
		DetachedCriteria criterion=DetachedCriteria.forClass(Classroom.class);
		criterion.createCriteria("school").add(Restrictions.eq("id",schoolId));
		criterion.add(Restrictions.eq("capacity", caps));
	    criterion.add(Restrictions.eq("status",
				StatusType.VALID));
	    return classroomDao.findAllByCriteria(criterion);
 	}
	
	public List<Classroom> findByName(String name,int max) {
		StringBuffer hql =  new StringBuffer("From Classroom where lower(name) like '%");
		hql.append(name);
		hql.append("%' and status='VALID'");
	    return classroomDao.findMultiAll(hql.toString(), 0, max);
 	}
	
	public List<Classroom> findByNameInSchool(String name,Long schoolId,int max) {
		StringBuffer hql =  new StringBuffer("From Classroom where lower(name) like '%");
		hql.append(name);
		hql.append("%'  and status='VALID' and school.id=");
		hql.append(schoolId);
		
	    return classroomDao.findMultiAll(hql.toString(), 0, max);
 	}
}
